package com.lkl.chat.util;

import okhttp3.HttpUrl;
import org.apache.commons.lang3.StringUtils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.InvalidParameterException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 授权工具类
 */
public class AuthorUtil {


    public static String genAuthUrl(String apiKey, String apiSecret, String host, String path) {
        if (StringUtils.isAnyBlank(apiKey, apiSecret, host, path)) {
            throw new InvalidParameterException("参数不能为空!");
        }
        try {
            String date = getRFC1123Date();
            return generateAuthorization(date, host, path, apiSecret, apiKey);
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     *  获取 RFC_1123 格式日期
     */
    public static String getRFC1123Date() {
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        format.setTimeZone(TimeZone.getTimeZone("GMT"));
        return format.format(new Date());
    }

    /**
     * 生成鉴权字符串
     * @param date 当前时间
     * @param host 请求地址
     * @param path
     * @param apiSecret
     * @param apiKey
     * @return
     */
    public static String generateAuthorization(String date, String host, String path, String apiSecret, String apiKey) {
        StringBuilder sb = new StringBuilder();
        sb.append("host: ").append(host).append("\n");
        sb.append("date: ").append(date).append("\n");
        sb.append("GET ").append(path).append(" HTTP/1.1");
        //SHA256加密
        Mac mac = null;
        String sha = "";
        try {
            mac = Mac.getInstance("hmacsha256");
            mac.init(new SecretKeySpec(apiSecret.getBytes(StandardCharsets.UTF_8), "hmacsha256"));
            byte[] hexDigits = mac.doFinal(sb.toString().getBytes());
            // Base64加密
            sha = Base64.getEncoder().encodeToString(hexDigits);
        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            throw new RuntimeException(e);
        }
        // 生成 authorization
        String authorization = String.format("api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"", apiKey, "hmac-sha256", "host date request-line", sha);
        authorization = Base64.getEncoder().encodeToString(authorization.getBytes(StandardCharsets.UTF_8)); //使用base64加密

        return Objects.requireNonNull(HttpUrl.parse("https://" + host + path)).newBuilder().
                addQueryParameter("authorization",authorization).//
                addQueryParameter("date", date).//
                addQueryParameter("host", host).//
                build().
                toString()
                .replace("https","wss");
    }
}
